/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DialogSelectUsers.java
 *
 * Created on 27.05.2011, 15:13:31
 */
package ru.icq.gui.dialogs;

import java.awt.Component;
import java.io.File;
import java.util.Iterator;
import java.util.Properties;
import java.util.ResourceBundle;
import org.apache.log4j.Logger;
import ru.icq.exceptions.CryptExceptions;
import ru.icq.exceptions.PropertiesExceptions;
import ru.icq.gui.frame.FrameICQ;
import ru.icq.io.DesEncrypter;
import ru.icq.io.FileProperties;
import ru.icq.utils.I18N;
import ru.icq.utils.Utils;

/**
 * Окно выбора пользователя.
 * @author Носов А.В.
 */
public class DialogSelectUsers extends javax.swing.JFrame {

    // Variables declaration
    private static final Logger log = Logger.getLogger(DialogSelectUsers.class);
    private ResourceBundle rb;
    
    private DesEncrypter crypt = new DesEncrypter();
    // End of variables declaration

    /** Creates new form DialogSelectUsers */
    public DialogSelectUsers() {
        
        rb = ResourceBundle.getBundle(this.getClass().getCanonicalName());
        
        initComponents();
        
        this.setSize(240, 255);
        Utils.setFrameCenter( (Component)this );
        Properties prop;
        try {
            prop = FileProperties.loadProperties();
            if (prop.getProperty("jICQ.last_user") != null) {
                comboBoxUsers.setSelectedItem(prop.getProperty("jICQ.last_user"));
            }
        } catch (PropertiesExceptions ex) {
            log.error("Ошибка загрузки настроект:", ex);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        comboBoxUsers = new javax.swing.JComboBox();
        buttonDeleteUsers = new javax.swing.JButton();
        testFieldPassword = new javax.swing.JPasswordField();
        checkBoxSavePassword = new javax.swing.JCheckBox();
        checkBoxDefault = new javax.swing.JCheckBox();
        buttonSelectUsers = new javax.swing.JButton();
        buttonCansel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(I18N.getString(rb, "Title"));
        setResizable(false);
        getContentPane().setLayout(new java.awt.GridBagLayout());

        comboBoxUsers.setToolTipText(I18N.getString(rb, "User"));
        comboBoxUsers.setPreferredSize(new java.awt.Dimension(100, 27));
        comboBoxUsers.setEditable(true);
        setUsers();
        comboBoxUsers.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboBoxUsersActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(15, 3, 5, 3);
        getContentPane().add(comboBoxUsers, gridBagConstraints);

        buttonDeleteUsers.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ru/icq/utils/icons/user_delete.png"))); // NOI18N
        buttonDeleteUsers.setToolTipText(I18N.getString(rb, "Delete"));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(15, 3, 5, 3);
        getContentPane().add(buttonDeleteUsers, gridBagConstraints);

        testFieldPassword.setToolTipText(I18N.getString(rb, "Password"));
        testFieldPassword.setPreferredSize(new java.awt.Dimension(170, 27));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(5, 3, 10, 3);
        getContentPane().add(testFieldPassword, gridBagConstraints);

        checkBoxSavePassword.setText(I18N.getString(rb, "Save"));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(10, 3, 1, 3);
        getContentPane().add(checkBoxSavePassword, gridBagConstraints);

        checkBoxDefault.setText(I18N.getString(rb, "Visible"));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(1, 3, 15, 3);
        getContentPane().add(checkBoxDefault, gridBagConstraints);

        buttonSelectUsers.setText(I18N.getString(rb, "Select"));
        buttonSelectUsers.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSelectUsersActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.insets = new java.awt.Insets(15, 3, 5, 3);
        getContentPane().add(buttonSelectUsers, gridBagConstraints);

        buttonCansel.setText(I18N.getString(rb, "Cansel"));
        buttonCansel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCanselActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.insets = new java.awt.Insets(15, 3, 5, 3);
        getContentPane().add(buttonCansel, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonSelectUsersActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSelectUsersActionPerformed
        
        String selectUser = (String) comboBoxUsers.getSelectedItem();
        char[] password = testFieldPassword.getPassword();
        
        
        if (selectUser == null) {
            Utils.isShowErrorMessage(this, I18N.getString(rb, "Error.UserName"));
            return;
        } 
        selectUser = selectUser.trim();
        if  (selectUser.equalsIgnoreCase("")) {
            Utils.isShowErrorMessage(this, I18N.getString(rb, "Error.UserName"));
            return;
        }
        if (password.length < 3) {
            Utils.isShowErrorMessage(this, I18N.getString(rb, "Error.UserPass"));
            return;
        }
        
        String userFolder = System.getProperty("user.dir") + File.separator + 
                    "Users" + File.separator + "jICQ." + selectUser;
        Properties prop = new Properties();
        
        if (comboBoxUsers.getSelectedIndex() < 0) {
            if (log.isInfoEnabled())
                log.info("Новый пользователь - " + selectUser);
            
            File newUser = new File(userFolder);
            if (newUser.mkdir()) {
//                new File(account + File.separator + "Devils").mkdir();
//                new File(account + File.separator + "History").mkdir();
                
                try {
                    prop.setProperty("jICQ.theme", "Default");
                    prop.setProperty("jICQ.name", selectUser);
                    prop.setProperty("jICQ.password", crypt.encrypt(new String(password)));
                    prop.setProperty("jICQ.save", String.valueOf(checkBoxSavePassword.isSelected()));
                    prop.setProperty("jICQ.visible", String.valueOf(checkBoxDefault.isSelected()));
                
                    FileProperties.createProperties(
                            userFolder + File.separator + "settings.properties", 
                            prop);
                } catch (PropertiesExceptions ex) {
                    log.error(ex.getError());
                } catch (CryptExceptions ex) {
                    Utils.isShowErrorMessage(this, ex.getMessage());
                    log.error(ex);
                    return;
                }
                
            } else {
                Utils.isShowErrorMessage(this, I18N.getString(rb, "Error.File"));
                log.error("Не могу создать пользователя.");
                return;
            }
        } else {
            prop = FileProperties.loadProperties(userFolder + File.separator + "settings.properties");
            if ((prop.getProperty("jICQ.name") != null) && 
                    (prop.getProperty("jICQ.password") != null)) {
                try {
                    String pass = crypt.decrypt(prop.getProperty("jICQ.password"));
//                    log.info(new String(testFieldPassword.getPassword()) + " = " + pass);
//                    log.info(selectUser + " = " + prop.getProperty("jICQ.name"));
                    if (!pass.equalsIgnoreCase(new String(testFieldPassword.getPassword())) || 
                            (!selectUser.equals(prop.getProperty("jICQ.name")))) {
                        Utils.isShowErrorMessage(this, I18N.getString(rb, "Error.UserCheck"));
                        return;
                    }
                } catch (CryptExceptions ex) {
                    Utils.isShowErrorMessage(this, ex.getMessage());
                    log.error(ex);
                    return;
                }
            } else {
                Utils.isShowErrorMessage(this, "Чет в файле настроек не хватает!!!");
                log.error("Чет в файле настроек не хватает!!!");
            }
        }
        
        try {
            Properties p = FileProperties.loadProperties();
            p.setProperty("jICQ.last_user", selectUser);
            FileProperties.saveProperties(p);
            FrameICQ f = new FrameICQ();
            f.setSelectUser(prop.getProperty("jICQ.name"));
            f.setVisible(true);
            this.dispose();
        } catch (PropertiesExceptions ex) {
            log.error(ex.getError());
        }
    }//GEN-LAST:event_buttonSelectUsersActionPerformed

    private void buttonCanselActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCanselActionPerformed
        System.exit(0);
    }//GEN-LAST:event_buttonCanselActionPerformed

    private void comboBoxUsersActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboBoxUsersActionPerformed
        if (comboBoxUsers.getSelectedIndex() >= 0) {
            log.info("action "+comboBoxUsers.getSelectedIndex());
            log.info("action "+comboBoxUsers.getSelectedItem().toString().trim());
            String user = System.getProperty("user.dir") + File.separator + 
                    "Users" + File.separator + comboBoxUsers.getSelectedItem().toString().trim() +
                    File.separator;
            log.info("action "+user);
            Properties prop = new Properties();
            prop = FileProperties.loadProperties(user + "settings.properties");
            
            if (prop != null) {
                
                if (prop.getProperty("jICQ.save") != null) 
                    checkBoxSavePassword.setSelected(
                            Boolean.parseBoolean(prop.getProperty("jICQ.save").trim()));
                if (prop.getProperty("jICQ.visible") != null)
                    checkBoxDefault.setSelected(
                            Boolean.parseBoolean(prop.getProperty("jICQ.visible").trim()));
                
                if (checkBoxSavePassword.isSelected()) {
                    try {
                        testFieldPassword.setText(crypt.decrypt(prop.getProperty("jICQ.password").trim()));
                    } catch (CryptExceptions ex) {
                        log.error(ex.getMessage());
                    }
                }
            }
        }
    }//GEN-LAST:event_comboBoxUsersActionPerformed

    /**
     * Устанавливает в выпадающий список созданных пользователей.
     */
    private void setUsers() {
        Iterator it = FileProperties.getUsers().values().iterator();
        while (it.hasNext()) {            
            File f = (File) it.next();
            String name = f.getName();
            comboBoxUsers.addItem(name.substring(name.indexOf(".")+1));
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new DialogSelectUsers().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonCansel;
    private javax.swing.JButton buttonDeleteUsers;
    private javax.swing.JButton buttonSelectUsers;
    private javax.swing.JCheckBox checkBoxDefault;
    private javax.swing.JCheckBox checkBoxSavePassword;
    private javax.swing.JComboBox comboBoxUsers;
    private javax.swing.JPasswordField testFieldPassword;
    // End of variables declaration//GEN-END:variables
}
